import * as vscode from 'vscode';
import * as child_process from 'child_process';
import * as path from 'path';
import * as fs from 'fs';

// 检测可用的包管理器
async function detectPackageManager(): Promise<string> {
    return new Promise<string>((resolve) => {
        // 首先检查pnpm是否可用
        child_process.exec('pnpm --version', (error) => {
            if (!error) {
                resolve('pnpm');
            } else {
                // 如果pnpm不可用，检查npm是否可用
                child_process.exec('npm --version', (error2) => {
                    if (!error2) {
                        resolve('npm');
                    } else {
                        // 如果都不可用，默认使用npm
                        resolve('npm');
                    }
                });
            }
        });
    });
}

// 支持的文件扩展名
// Biome原生支持的文件扩展名
const SUPPORTED_EXTENSIONS = [
    '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs',
    '.json', '.jsonc',
    '.css'
];

// Biome原生支持的语言ID
const SUPPORTED_LANGUAGE_IDS = [
    'javascript', 'typescript', 'javascriptreact', 'typescriptreact',
    'json', 'jsonc',
    'css'
];

// 有限支持的文件扩展名（需要额外配置或支持不完整）
const LIMITED_SUPPORT_EXTENSIONS = [
    '.scss', '.less',
    '.html',
    '.md',
    '.yml', '.yaml'
];

// 有限支持的语言ID
const LIMITED_SUPPORT_LANGUAGE_IDS = [
    'scss', 'less',
    'html',
    'markdown',
    'yaml'
];

// 特定配置文件
const CONFIG_FILES = [
    'biome.json', 'tsconfig.json', 'jsconfig.json', 
    'package.json', '.eslintrc.json', '.prettierrc.json'
];

// 检查Biome环境是否可用
async function checkBiomeEnvironment(): Promise<boolean> {
	try {
		// 检查当前工作区是否有package.json
		const workspaceFolders = vscode.workspace.workspaceFolders;
		if (!workspaceFolders || workspaceFolders.length === 0) {
			return false;
		}

		const workspaceRoot = workspaceFolders[0].uri.fsPath;
		const packageJsonPath = path.join(workspaceRoot, 'package.json');

		// 检查package.json是否存在
		if (fs.existsSync(packageJsonPath)) {
			const packageJsonContent = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));

			// 检查dependencies或devDependencies中是否有biome
			const dependencies = {
				...packageJsonContent.dependencies,
				...packageJsonContent.devDependencies
			};

			if (dependencies && (dependencies.biome || dependencies['@biomejs/biome'])) {
				return true;
			}
		}

		// 检查全局安装的Biome
		return new Promise<boolean>((resolve) => {
			const checkCommand = process.platform === 'win32' ? 'where biome' : 'which biome';

			child_process.exec(checkCommand, (error, stdout) => {
				if (error) {
					// 检查pnpm dlx biome
					child_process.exec('pnpm dlx biome --version', (error2) => {
						resolve(!error2);
					});
				} else {
					resolve(stdout.trim().length > 0);
				}
			});
		});
	} catch (error) {
		return false;
	}
}

// 显示Biome环境检查警告
async function showBiomeEnvironmentWarning() {
	const hasBiome = await checkBiomeEnvironment();

	if (!hasBiome) {
		const selection = await vscode.window.showWarningMessage(
			'Biome环境未检测到。插件需要Biome才能正常工作。',
			'安装Biome',
			'查看文档',
			'忽略'
		);

		if (selection === '安装Biome') {
			// 打开Biome安装文档
			vscode.env.openExternal(vscode.Uri.parse('https://biomejs.dev/guides/getting-started/'));
		} else if (selection === '查看文档') {
			// 打开插件使用文档
			vscode.env.openExternal(vscode.Uri.parse('https://gitcode.com/lenkaset/use-biome-check#readme'));
		}
	}

	return hasBiome;
}

// 当插件被激活时调用此方法
// 你的插件在第一次执行命令时被激活
export function activate(context: vscode.ExtensionContext) {

	console.log('Congratulations, your extension "use-biome-check" is now active!');

	// 注册Hello World命令
	let helloWorldDisposable = vscode.commands.registerCommand('use-biome-check.helloWorld', () => {
		// 显示消息框给用户
		vscode.window.showInformationMessage('Hello World from use-biome-check!');
	});

	// 在插件激活时检查Biome环境
	showBiomeEnvironmentWarning();

	// 注册Biome Check命令（支持文件和文件夹）
	let disposable = vscode.commands.registerCommand('use-biome-check.biomeCheckFile', async (uri?: vscode.Uri) => {
		// 在执行命令前检查Biome环境
		const hasBiome = await checkBiomeEnvironment();
		if (!hasBiome) {
			vscode.window.showErrorMessage('Biome环境未检测到。请先安装Biome才能使用此功能。');
			return;
		}
		// 获取当前路径（文件或文件夹）
		let targetPath: string | undefined;
		let isDirectory = false;

		if (uri && uri.fsPath) {
			// 从右键菜单传递的URI获取路径
			targetPath = uri.fsPath;
			// 检查是否为文件夹
			try {
				const stat = await vscode.workspace.fs.stat(uri);
				isDirectory = stat.type === vscode.FileType.Directory;
			} catch (error) {
				// 如果无法获取文件状态，默认为文件
				isDirectory = false;
			}
		} else {
			// 从当前活动的编辑器获取文件路径
			const editor = vscode.window.activeTextEditor;
			if (editor) {
				targetPath = editor.document.uri.fsPath;
				isDirectory = false;
			}
		}

		if (!targetPath) {
			vscode.window.showErrorMessage('无法获取路径，请确保已打开文件或右键点击了文件/文件夹');
			return;
		}

		// 如果是文件，检查文件格式
		if (!isDirectory) {
			// 检查文件扩展名支持
			if (!isFileSupported(targetPath)) {
				const fileName = path.basename(targetPath);
				
				// 检查是否为有限支持的文件类型
				if (isFileLimitedSupport(targetPath)) {
					const fileExtension = '.' + targetPath.toLowerCase().split('.').pop();
					const selection = await vscode.window.showWarningMessage(
						`Biome 对 ${fileExtension} 文件的支持有限或需要额外配置。是否继续？`,
						'继续',
						'取消'
					);
					if (selection !== '继续') {
						return;
					}
				} else {
					vscode.window.showWarningMessage(
						`Biome 不支持格式化 ${fileName} 文件类型。支持的类型: ${SUPPORTED_EXTENSIONS.join(', ')}`
					);
					return;
				}
			}
			
			// 检查语言ID支持（仅当从编辑器执行时）
			if (!uri && !isLanguageSupported()) {
				const editor = vscode.window.activeTextEditor;
				if (editor) {
					const languageId = editor.document.languageId;
					
					// 检查是否为有限支持的语言类型
					if (isLanguageLimitedSupport()) {
						const selection = await vscode.window.showWarningMessage(
							`Biome 对 ${languageId} 语言的支持有限或需要额外配置。是否继续？`,
							'继续',
							'取消'
						);
						if (selection !== '继续') {
							return;
						}
					} else {
						vscode.window.showWarningMessage(
							`Biome 不支持格式化 ${languageId} 语言类型。支持的语言: ${SUPPORTED_LANGUAGE_IDS.join(', ')}`
						);
						return;
					}
				}
			}
		}

		// 执行Biome Check命令
		try {
			await runBiomeCheck(targetPath, isDirectory);
		} catch (error) {
			vscode.window.showErrorMessage(`执行Biome Check失败: ${error}`);
		}
	});

	context.subscriptions.push(helloWorldDisposable, disposable);
}

// 创建输出通道
let outputChannel: vscode.OutputChannel;

// 运行Biome Check命令（支持文件和文件夹）
async function runBiomeCheck(targetPath: string, isDirectory: boolean): Promise<void> {
	// 获取配置
	const config = vscode.workspace.getConfiguration('useBiomeCheck');
	const autoSwitchToOutput = config.get<boolean>('autoSwitchToOutput', false);
	const showOutputInfo = config.get<boolean>('showOutputInfo', true);

	// 只在需要显示输出信息时创建输出通道
	if (showOutputInfo || autoSwitchToOutput) {
		if (!outputChannel) {
			outputChannel = vscode.window.createOutputChannel('Biome Check');
		}

		// 根据配置决定是否显示输出通道
		if (autoSwitchToOutput) {
			outputChannel.show(true);
		}
	}

	// 显示进度通知
	const progressTitle = isDirectory ? `Running Biome Check on folder: ${path.basename(targetPath)}...` : 'Running Biome Check...';

	await vscode.window.withProgress({
		location: vscode.ProgressLocation.Notification,
		title: progressTitle,
		cancellable: false
	}, async (_progress) => {
		return new Promise<void>(async (resolve, reject) => {
			// 检测可用的包管理器
			const packageManager = await detectPackageManager();
			
			// 构建命令
			const command = packageManager;
			const args = ['biome', 'check', targetPath, '--write'];

			// 获取当前工作目录
			const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(targetPath));
			let cwd: string;

			if (isDirectory) {
				// 如果是文件夹，使用文件夹本身作为工作目录
				cwd = targetPath;
			} else {
				// 如果是文件，使用文件所在目录
				cwd = workspaceFolder ? workspaceFolder.uri.fsPath : path.dirname(targetPath);
			}

			// 根据配置决定是否输出命令信息
			if (showOutputInfo && outputChannel) {
				outputChannel.appendLine(`[${new Date().toLocaleTimeString()}] 执行 Biome Check:`);
				outputChannel.appendLine(`命令: ${command} ${args.join(' ')}`);
				outputChannel.appendLine(`工作目录: ${cwd}`);
				outputChannel.appendLine('---');
			}

			// 执行命令
			const process = child_process.spawn(command, args, {
				cwd: cwd,
				shell: true,
				stdio: 'pipe'
			});

			let stdout = '';
			let stderr = '';

			process.stdout.on('data', (data) => {
				const output = data.toString();
				stdout += output;
				if (outputChannel) {
					outputChannel.append(output);
				}
			});

			process.stderr.on('data', (data) => {
				const output = data.toString();
				stderr += output;
				if (outputChannel) {
					outputChannel.append(output);
				}
			});

			process.on('close', (code) => {
				if (showOutputInfo && outputChannel) {
					outputChannel.appendLine('---');
				}
				if (code === 0) {
					const successMessage = isDirectory
						? `Biome Check 完成: 文件夹 ${path.basename(targetPath)}`
						: `Biome Check 完成: ${path.basename(targetPath)}`;
					if (showOutputInfo && outputChannel) {
						outputChannel.appendLine(`✅ ${successMessage}`);
						outputChannel.appendLine('');
					}
					resolve();
				} else {
					if (showOutputInfo && outputChannel) {
						outputChannel.appendLine(`❌ Biome Check 失败 (退出码: ${code})`);
					}
					reject(new Error(`Biome Check 失败 (退出码: ${code}): ${stderr || stdout}`));
				}
			});

			process.on('error', (error) => {
				if (outputChannel) {
					outputChannel.appendLine(`❌ 执行命令失败: ${error.message}`);
				}
				reject(new Error(`执行命令失败: ${error.message}`));
			});
		});
	});
}

// 检查文件是否支持
function isFileSupported(filePath: string): boolean {
    const filePathLower = filePath.toLowerCase();
    
    // 检查文件扩展名
    const extension = '.' + filePathLower.split('.').pop();
    if (SUPPORTED_EXTENSIONS.includes(extension)) {
        return true;
    }
    
    // 检查特定配置文件
    const fileName = filePathLower.split(/[\\/]/).pop() || '';
    if (CONFIG_FILES.includes(fileName)) {
        return true;
    }
    
    return false;
}

// 检查文件是否为有限支持类型
function isFileLimitedSupport(filePath: string): boolean {
    const filePathLower = filePath.toLowerCase();
    const extension = '.' + filePathLower.split('.').pop();
    return LIMITED_SUPPORT_EXTENSIONS.includes(extension);
}

// 检查语言是否为有限支持类型
function isLanguageLimitedSupport(): boolean {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        return false;
    }
    
    const languageId = editor.document.languageId;
    return LIMITED_SUPPORT_LANGUAGE_IDS.includes(languageId);
}

// 检查当前编辑器语言是否支持
function isLanguageSupported(): boolean {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        return false;
    }
    
    const languageId = editor.document.languageId;
    return SUPPORTED_LANGUAGE_IDS.includes(languageId);
}

// 当插件被停用时调用此方法
export function deactivate() {
	if (outputChannel) {
		outputChannel.dispose();
	}
}